package com.elinkway.infinitemovies.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;

import com.elinkway.infinitemovies.async.RequestCloudDiskTask;
import com.elinkway.infinitemovies.async.RequestStreamResultListener;
import com.elinkway.infinitemovies.bean.CloudDiskBean;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bigdata.BigDataPlayReporter;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.http.requesttask.RequestDoPlayRecordTask;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;
import com.elinkway.infinitemovies.ui.activity.play.PlayDecodeMananger;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.CDEManager;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.UmengPostConstant;
import com.le123.ysdq.IRemoteService;
import com.le123.ysdq.LiteappCallback;
import com.letv.pp.func.CdeHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: liuxiaojiang(liuxiaojiang@lvideo.com)
 * Date: 2016-03-31
 * Time: 23:17
 * Description: FIXME
 */
public class LiteService extends Service {

    private RequestCloudDiskTask mRequestCloudTask;
    /**
     * 云盘播放地址
     */
    private ArrayList<String> mCloudPlayUrls;

    private String mCloundId = "";

    private String mType = "";

    private CDEManager mCDEManager;

    private BigDataPlayReporter bigDataPlayReporter;

    private CdeHelper cdeHelper;

    private static final String TAG = "LiteService";

    private LiteappCallback mCallback;

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("LiteSevice start...." + "Thread: " + Thread.currentThread().getName());
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("LiteService onBind");
        return mBinder;
    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub(){

        @Override
        public int getPid() throws RemoteException {
            return android.os.Process.myPid();
        }

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
            System.out.println("Thread: " + Thread.currentThread().getName());
        }

        @Override
        public String getPlayInfo(String couldId, LiteappCallback callback) throws RemoteException {
            System.out.println("通过云盘id获取播放的数据:::" + "couldId: "+ couldId);
            mCallback = callback;
            requestCloudPlay(couldId, "1");
            return "http://doplay";
        }

        @Override
        public void savePlayRecord(String aid, String name, String subsrc, String vid, long playTime, String porder, String vt) throws RemoteException {
            if(aid == null){
                return;
            }
            PlayRecord record = new PlayRecord();
            record.setAid(aid);
            record.setName(name);
            record.setSite(subsrc);
            record.setVid(vid);
            record.setSeekHistory(playTime);
            record.setTime(System.currentTimeMillis());
            record.setEpisodeName(porder);
            record.setPorder(porder);
            record.setVt(vt);
            SharedPreferences mLoginSP = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
            if(mLoginSP != null && !TextUtils.isEmpty(mLoginSP.getString(LoginActivity.TOKEN, ""))){
                List<PlayRecord> list = new ArrayList<PlayRecord>();
                list.add(record);
                new RequestDoPlayRecordTask(LiteService.this, list, "add").start();
            }else{
                new PlayRecordDao(LiteService.this).save(record);
            }
        }

    };

    /**
     * 请求云盘地址
     *
     * @param type
     */
    private void requestCloudPlay(String couldId, String type) {
        mCDEManager = CDEManager.getInstance(this);
        cdeHelper = mCDEManager.getmCdeHelper();
        if(cdeHelper.isReady()){
        }else{
            cdeHelper.start();
        }
        bigDataPlayReporter = new BigDataPlayReporter();
        // 执行网盘相关请求
        if (null != mRequestCloudTask && !mRequestCloudTask.isCancelled()) {
            mRequestCloudTask.cancel();
        }
        mRequestCloudTask = new RequestCloudDiskTask(this);
        mRequestCloudTask.setParameter(couldId, type);
        mCloundId = couldId;
        mType = type;
        mRequestCloudTask.setmListener(new CloudDiskRequestListener());
        mRequestCloudTask.start();
        UmengEventPoster.doEventPost(UmengPostConstant.PlayVideo_nets); //播云盘源友盟上报
    }

    public class CloudDiskRequestListener implements
            RequestStreamResultListener<CloudDiskBean> {

        @Override
        public boolean onRequestFailed() {
            try {
                mCallback.getPlayUrlFail("获取播放地址失败");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, CloudDiskBean result) {
            // 如果首请求云盘MP4类型播放地址为空时则进行二次请求 请求m3u8播放源
            if (null != result && null != result.getmPlayUrls()
                    && result.getmPlayUrls().size() > 0) {
                mCloudPlayUrls = result.getmPlayUrls();
                if (0 < mCloudPlayUrls.size()) {
                    String cloudPlayUrl = mCloudPlayUrls
                            .get(0);
                    String resultUrl = "";

                    // 判断当前CDE服务是否启动
                    if (cdeHelper.isReady()) {
                        LogUtils.e(TAG, "!!!!!!!CDE服务是启动的");
                        if (!TextUtils.isEmpty(cloudPlayUrl)) {
                            LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!!!!!request cloud play data sucess and cloudPlayUrl is " + cloudPlayUrl);
                            LogUtils.e("wym", "cloud cde called and cur uuid " + bigDataPlayReporter.getUUID());
                            bigDataPlayReporter.genUUID(); // 在拿到cde调度地址时，构造当前播放器uuid
                            LogUtils.e("wym", "!!!!!!!!!!!!!!!!!!!!!before addPlatCode cloudPlayUrl is " + cloudPlayUrl);
                            String uuid = bigDataPlayReporter.getUUID();
                            String vid = mCloundId; // vid取cloudId
                            // add platParam && (add uuid,vid || uuid,liveid)
                            cloudPlayUrl = PlayerUtils
                                    .addPlatCode(cloudPlayUrl, uuid, vid);
                            LogUtils.e("wym", "!!!!!!!!!!!!!!!!!!!!!after addPlatCode cloudPlayUrl is " + cloudPlayUrl);
                            // CdeHelper cdeHelper =
                            // mCDEManager.getmCdeHelper();
                            String mLinkShellUrl = cdeHelper.getLinkshellUrl(cloudPlayUrl);
                            LogUtils.e("wym", "$$$$$$$$mLinkShellUrl$$$$$$" + mLinkShellUrl);
                            resultUrl = cdeHelper.getPlayUrl(mLinkShellUrl);
                        }
                        if (!StringUtil.isEmpty(resultUrl)) {
                            LogUtils.e("wym", "云盘cdeurl-----------" + resultUrl);
                            System.out.println("playurl:" + resultUrl);
//                            doPlay(PlayerUtils.DEFAULT_PLAYER_TYPE, resultUrl);
                            if(mCallback != null){
                                try {
                                    mCallback.getPlayUrlSuccess(resultUrl);
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                        }else{
                            try {
                                mCallback.getPlayUrlFail("获取播放地址失败");
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
//                        mCdeStatusReiver = new CDEStatusReceiver();
//                        mSelfOwnActivity.registerReceiver(mCdeStatusReiver,
//                                new IntentFilter(CdeService.ACTION_CDE_READY));
//                        mCDEManager.startCde();
                        requestCloudPlay(mCloundId, mType);
                    }

                }else{
                    try {
                        mCallback.getPlayUrlFail("获取播放地址失败");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                // 如果当前请求云盘的播放格式是M3u8那么可以开始请求MP4播放源
                if (mType == PlayDecodeMananger.CLOUD_M3U8) {
                    requestCloudPlay(mCloundId, "0");
                }else{
                    try {
                        mCallback.getPlayUrlFail("获取播放地址失败");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void onPreRequest() {

        }

        @Override
        public boolean onRequestFailed(String code, String msg) {
            return false;
        }
    }
}
